package org.example.spring.simple.framework.aop.proxy;

import org.example.spring.simple.framework.aop.intercept.ZMethodInvocation;
import org.example.spring.simple.framework.aop.support.ZAdvicedSupport;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

public class ZJdkDynamicAopProxy implements ZAopProxy, InvocationHandler {
    private ZAdvicedSupport config;

    public ZJdkDynamicAopProxy(ZAdvicedSupport config) {
        this.config = config;
    }

    /**
     * 把原对象传入，获得代理对象
     * @return
     */
    @Override
    public Object getProxy() {
        return getProxy(this.config.getTargetClass().getClassLoader());
    }

    @Override
    public Object getProxy(ClassLoader classLoader) {
        return Proxy.newProxyInstance(classLoader, this.config.getTargetClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //将每个JoinPoint即被代理方法封装成一个拦截器，组成拦截器链
        List interceptorsAndDynamicMethodMatchers = config.getInterceptorsAndDynamicInterceptionAdvice(method, this.config.getTargetClass());
        ZMethodInvocation invocation = new ZMethodInvocation(proxy, this.config.getTarget(), method, args,
                this.config.getTargetClass(), interceptorsAndDynamicMethodMatchers);
        return invocation;
    }
}
